<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-row :gutter="10">
        <a-col :md="20" :sm="24">
          <a-button v-if="hasPerm('PB_Location.Add')" type="primary" icon="plus" @click="hanldleAdd()">新建</a-button>
          <a-button
            v-if="hasPerm('PB_Location.Delete')"
            type="primary"
            icon="minus"
            @click="handleDelete(selectedRowKeys)"
            :disabled="!hasSelected()"
            :loading="loading"
            >删除</a-button
          >
          <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
          <a-radio-group
            style="margin-right: 8px"
            default-value="asc"
            @change="getDataList()"
            button-style="solid"
            v-model="sorter.order"
          >
            <a-radio-button value="asc"> <a-icon type="arrow-up" /> 正序 </a-radio-button>
            <a-radio-button value="desc"> <a-icon type="arrow-down" /> 倒序 </a-radio-button>
          </a-radio-group>
          <a-popconfirm
            title="请选择打印的类型"
            cancel-text="批量A4"
            ok-text="批量条码"
            @confirm="confirms"
            @cancel="cancels"
          >
            <a-button
              type="primary"
              v-if="hasPerm('PB_Location.Print')"
              @click="rowsadd(selectedRowKeys)"
              :disabled="!hasSelecteds()"
              :loading="loading"
              >批量打印</a-button
            >
          </a-popconfirm>
        </a-col>
        <a-button v-if="hasPerm('PB_Location.Leading')" type="primary" @click="hanldleLeading()">导入货位</a-button>
      </a-row>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-select v-model="queryParam.StorId" @change="SelectOrgan" allowClear placeholder="收货仓库">
              <a-select-option v-for="item in ParentIdTreeData" :value="item.Id" :key="item.Id">
                {{ item.Name }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-select @change="ListName" allowClear v-model="queryParam.AreaId" placeholder="选择库区">
                <a-select-option v-for="(item, index) in LanewayList" :value="item.Id" :key="index"
                  >{{ item.Name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-select v-model="queryParam.RackId" @change="Rackchange" placeholder="选择货架" allowClear>
                <a-select-option v-for="(item, index) in RackList" :value="item.Id" :key="index"
                  >{{ item.Name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.Keyword" placeholder="货位名称/编码" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="Reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 560 }"
      :columns="columns"
      :rowKey="(row) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <span slot="IsForbid" slot-scope="text, record">
        <template>
          <a-tag v-if="record.IsForbid === false" color="red"> 停用 </a-tag>
          <a-tag v-else color="green"> 启用 </a-tag>
        </template>
      </span>

      <span slot="IsDefault" slot-scope="text, record">
        <template>
          <a-tag v-if="record.IsDefault === false" color="red"> 否 </a-tag>
          <a-tag v-else color="green"> 是 </a-tag>
        </template>
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('PB_Location.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider v-if="hasPerm('PB_Location.Edit')" type="vertical" />
          <a-popconfirm
            title="请选择打印的类型"
            cancel-text="打印A4"
            ok-text="打印条码"
            @confirm="confirm"
            @cancel="cancel"
          >
            <a v-if="hasPerm('PB_Location.Print')" @click="print(record.Id, record.Code)">打印</a></a-popconfirm
          >
          <a-divider v-if="hasPerm('PB_Location.Print')" type="vertical" />
          <a v-if="hasPerm('PB_Location.Delete')" @click="handleDelete([record.Id])">删除</a>
          <span>
            <a-divider type="vertical" />
            <a @click="handledetail(record.Id)">货位明细</a>
          </span>
        </template>
      </span>
      <template slot="dataIndex" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
    </a-table>
    <a-drawer
      width="30%"
      title="选择打印机"
      :visible="boxflag"
      :confirm-loading="boxLoading"
      @ok="handleOk"
      @close="boxflag = false"
    >
      <div style="margin-bottom: 7px">
        <p>
          货位编号:
          <a-input v-model="codes" disabled />
        </p>
        <p>
          货位编号:
          <a-input v-model="Print.LocationID" v-show="false" />
        </p>

        <p style="margin-bottom: 7px">
          打印机:
          <a-select style="width: 100%" v-model="Print.PrintID">
            <a-select-option v-for="item in printlist" :key="item.Id" :value="item.Id">
              {{ item.Name }}
            </a-select-option>
          </a-select>
        </p>
      </div>
      <div style="height: 10px"></div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button
          :style="{ marginRight: '8px' }"
          @click="
            () => {
              boxflag = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="handleOk">打印</a-button>
      </div>
    </a-drawer>
    <edit-form ref="editForm" :parentObj="this"></edit-form>
    <leading-form ref="leadingForm" :parentObj="this"></leading-form>
    <DispatchPrint2 ref="dispatchPrint2" :parentObj="this"></DispatchPrint2>
    <DispatchPrint ref="dispatchPrint" :parentObj="this"></DispatchPrint>
    <BatchPrinting ref="batchPrinting" :parentObj="this"> </BatchPrinting>
    <DetailsList ref="DetailsList" :parentObj="this"></DetailsList>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
// import EnumName from '../../../components/BaseEnum/BaseEnumName'
import UploadFile from '../../../components/CUploadFile/CUploadFile'
import LeadingForm from './LeadingForm'
import DispatchPrint2 from './DispatchPrint2.vue'
import DispatchPrint from './DispatchPrint.vue'
import BatchPrinting from './BatchPrinting'
import DetailsList from './DetailsList'
// const filterYesOrNo = (value, row, index) => {
//   if (value) return '是'
//   else return '否'
// }

const columns = [
  {
    title: '序号',
    align: 'center',
    width: '5%',
    scopedSlots: { customRender: 'dataIndex' },
  },
  { title: '货位编号', dataIndex: 'Code' },
  { title: '货位名称', dataIndex: 'Name' },
  { title: '仓库', dataIndex: 'Department.Name' },
  { title: '库区', dataIndex: 'PB_StorArea.Name' },
  // { title: '巷道', dataIndex: 'PB_Laneway.Name' },
  { title: '货架', dataIndex: 'PB_Rack.Name' },
  // { title: '余量', dataIndex: 'OverVol' },
  { title: '状态', dataIndex: 'IsForbid', scopedSlots: { customRender: 'IsForbid' } }, //是否禁用
  { title: '默认', dataIndex: 'IsDefault', scopedSlots: { customRender: 'IsDefault' } }, //是否默认库位
  // { title: '故障码', dataIndex: 'ErrorCode', width: '6' },
  // { title: '备注', dataIndex: 'Remarks', width: '10%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, align: 'center', width: '22%' },
]

export default {
  components: {
    EditForm,
    // EnumName,
    UploadFile,
    LeadingForm,
    DispatchPrint2,
    DispatchPrint,
    BatchPrinting,
    DetailsList,
  },
  async created() {
    await this.getDataList()
    await this.Organ()
    this.getprintlist()
  },
  mounted() {},
  data() {
    return {
      LanewayList: [],
      RackList: [],
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], //设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        defaultCurrent: 1,
        onChange: this.onPageChange.bind(this),
      },
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      loading: false,
      columns,
      queryParam: {
        // RackId: '',
        // AreaId: ''
      },
      selectedRowKeys: [],
      entity: {},
      fileList: [],
      ParentIdTreeData: [],
      Print: {},
      PrintID: '',
      printlist: [],
      boxLoading: false,
      boxflag: false,
      printflag: false,
      disabled: true,
      confirmLoading: false,
      codes: '',
      pid: '',
      codess: '',
      selectedRows: [],
      selectid: '',
    }
  },

  methods: {
    handledetail(id) {
      this.$refs.DetailsList.openForm(id, '货位明细')
    },
    Reset() {
      this.queryParam = {}

      this.getDataList()
    },
    //打印二维码
    rowsadd(id) {
      if (id.length == 0) {
        this.$message.warning('请选择要打印的货位')
        return
      }
      this.Print.LocationID = id
      this.selectid = id
    },
    cancel() {
      this.$refs.batchPrinting.openDrawer(this.pid, '打印货位')
    },
    handleOk() {
      this.$http.post('/PB/PB_Location/SelectLocationID', this.Print).then((res) => {
        if (res.Success) {
          this.$message.success('打印成功')
          this.boxLoading = false
          this.boxflag = false

          this.getDataList()
        } else {
          this.boxLoading = false
          this.$message.error(res.Msg)
        }
      })
    },
    confirms() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择要打印的库区')
        return
      }
      this.boxflag = true
      this.boxLoading = false
    },
    cancels() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择要打印的货位')
        return
      }
      this.$refs.batchPrinting.openDrawer(this.selectid, '批量打印货位')
    },
    onPageChange(current) {
      this.pagination.current = current
    },
    confirm() {
      this.boxflag = true
      this.boxLoading = false
    },
    getprintlist() {
      this.$http.post('/PB/PB_JobBooking/GetPrinterListData?PrintType=' + 'PrintLocation').then((res) => {
        this.printlist = res.Data
      })
    },
    ListName(a) {
      delete this.queryParam.RackId
      this.getracklist(a)
    },
    handlePrint(id) {
      this.$refs.batchPrinting.openDrawer(id, '打印货位')
    },
    Rackchange(a) {
      this.queryParam.RackId = a
    },
    async Organ() {
      await this.$http.post('/PB/PB_PackList/GetDetpList', {}).then((resJson) => {
        if (resJson.Success) {
          this.ParentIdTreeData = resJson.Data
        }
      })
    },
    async GetStorAreaList(id) {
      this.loading = true
      await this.$http.post('/PB/PB_StorArea/GetDataListByStor?storId=' + id).then((resJson) => {
        console.log(resJson)
        this.loading = false
        this.LanewayList = resJson.Data
      })
    },
    async getracklist(a) {
      console.log(a)
      await this.$http.post('/PB/PB_Rack/QueryRackDataAsyncareaid?areaId=' + a).then((resJson) => {
        console.log(resJson)
        this.RackList = resJson.Data
      })
    },
    SelectOrgan(SelectOrgan) {
      delete this.queryParam.AreaId
      this.LanewayList = []
      this.RackList = []
      delete this.queryParam.RackId
      this.GetStorAreaList(SelectOrgan)
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []
      console.log(this.queryParam)
      this.loading = true
      this.$http
        .post('/PB/PB_Location/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.codes = selectedRows.map((item) => item.Code).join(',')
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd() {
      this.$refs.editForm.openForm(null, '新建货位')
    },
    handleEdit(id) {
      this.$refs.editForm.openForm(id, '编辑货位')
    },
    print(id, Code) {
      this.Print.LocationID = [id]
      this.codes = Code
      this.pid = [id]
      //  this.boxflag = true
      // this.boxLoading = false
      // this.$http.post('/PB/PB_Location/SelectLocationID?ID=' + id, {}).then(res => {
      //   console.log(res)
      //   if (res.Success == true) {
      //     this.$message.success('打印成功!')
      //   } else {
      //     this.$message.error(res.Msg)
      //   }
      //   // this.Headerlist = res.Data
      //   // res.Data.forEach(mo => {
      //   //   mo.DispatchDate = mo.DispatchDate.substring(0, 10)
      //   // })
      // })
      // this.$refs.dispatchPrint.openDrawer(id, '打印货位')
    },
    hasSelecteds() {
      return this.selectedRowKeys.length > 0
    },
    hanldleLeading() {
      this.$refs.leadingForm.openForm(null, '导入货位')
    },
    handleDelete(ids) {
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk() {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/PB/PB_Location/DeleteData', ids).then((resJson) => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        },
      })
    },
    handleEnable(Location, prop, enable) {
      var thisObj = this
      var entity = { ...Location }
      entity[prop] = enable
      this.$confirm({
        title: '确认' + (enable ? '启用' : '停用') + '吗?',
        onOk() {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/PB/PB_Location/SaveData', entity).then((resJson) => {
              resolve()
              if (resJson.Success) {
                thisObj.$message.success('操作成功!')
                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        },
      })
    },
  },
}
</script>
<style>
@media screen and (max-width: 1366px) {
  .ant-select-tree {
    max-height: 300px;
  }
}
.ant-select-tree {
  max-height: 300px;
}
</style>
